#Block.py

import web
import json
from Gcode import Gcode

db = web.database(dbn='sqlite', db='/etc/debrew/debrew')

class Block:
    def __init__(self, attrs):
        self._attrs = attrs
        for a, b in attrs.items():
            setattr(self, a, b)

    def save(self):
        db.update('blocks', where="id=$id", vars=self.attrs)

    @staticmethod
    def get_by_id(id):
        try:
            return Block(db.select('blocks', where='id=$id', vars=locals())[0])
        except IndexError:
            return None

    @staticmethod
    def get_all_by_section_id(section_id):
        blocks = []
        for block in db.select('blocks', order="idx", where='section_id = $section_id', vars=locals()):
            blocks.append(Block(block))
        return blocks

    ''' compiles and returns the block as g-codes '''
    def get_gcodes(self):
        settings = json.loads(self.settings)
        settings = dict((k.lower(), v) for k,v in settings.iteritems())
        type = self.name.lower().strip()

        if type ==  "reset":
            gcodes  = "G28     ; Home steppers\n";
            gcodes += "M90     ; Absolute coordinates\n"; 
            return gcodes;
        elif type ==  "circle":
            if not Gcode.params_ok(settings, ["time", "radius"]):
                return ";circle parameter error\n"
            return Gcode.make_circle(settings["radius"], settings["time"])
        elif type=="shake":
            if not Gcode.params_ok(settings, ["times", "seconds"]):
                return ";Shake parameter error\n"
            return Gcode.make_shake(settings["times"], settings["seconds"])
        elif type=="move":
            if not Gcode.params_ok(settings, ["x", "y", "z"]):
                return ";Move parameter error\n"
            return Gcode.G0(settings["x"], settings["y"], settings["z"], 10000)
        elif type == "wait":
            if not Gcode.params_ok(settings, ["seconds"]):
                return "; Wait paramters error\n"
            return "G4 S"+str(settings["seconds"])+"; Wait (seconds)\n"
        elif type == "temp": 
            if not Gcode.params_ok(settings, ["degrees", "wait"]):
                return "; Temperature paramters error (degrees, wait)\n"
            gcodes = "T0; Select water\n"
            if bool(int(settings["wait"])):
                gcodes += "M109 S"+str(settings["degrees"])+" ; Set water temperature and wait\n"
            else:
                gcodes += "M104 S"+str(settings["degrees"])+" ; Set water temperature\n"
            return gcodes
        elif type == "coarseness":
            if not Gcode.params_ok(settings, ["coarseness"]):
                return "; Coarseness parameters error \n"
            return Gcode.coarseness(settings["coarseness"])
        elif type == "grinder":
            if not Gcode.params_ok(settings, ["on"]):
                return "; Grinder missing paramter 'on' \n"
            return Gcode.grinder(settings["on"])
        elif type == "water":
            if not Gcode.params_ok(settings, ["amount"]):
                return "; Water missing parameter 'amount' \n"
            return Gcode.water(settings["amount"])
        elif type == "stop":
            return Gcode.stop()
        return "; unknown gcode: "+str(type)+"\n"


    
